package com.lbb.mall.product.service.impl;

import com.lbb.mall.product.dao.CategoryBrandRelationDao;
import com.lbb.mall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbb.common.utils.PageUtils;
import com.lbb.common.utils.Query;

import com.lbb.mall.product.dao.CategoryDao;
import com.lbb.mall.product.entity.CategoryEntity;
import com.lbb.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        //1.首先查询出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装成父子的树形结构
        //stream.filter()：https://www.jianshu.com/p/24af4f3ab046，https://blog.csdn.net/u010679782/article/details/109529626
        //https://blog.csdn.net/icarusliu/article/details/79495534
        List<CategoryEntity> level1Menu = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid().longValue() == 0//查询出parentcid为0的元素
        ).map((menu)->{//map：元素一对一转换：使用传入的Function对象对Stream中的所有元素进行处理，返回的Stream对象中的元素为原元素处理后的结果
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2) -> {
            return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menu;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 后期实现，删除之前需要判断待删除的菜单那是否被别的地方所引用

        baseMapper.deleteBatchIds(asList);

    }

    //递归查询所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //查询子菜单，注意此处应该用longValue()来比较，否则会出先bug，因为parentCid和catId是long类型
            return categoryEntity.getParentCid().longValue() == root.getCatId().longValue();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
            //sorted用法：https://vimsky.com/examples/detail/java-method-java.util.stream.Stream.sorted.html
            //https://blog.csdn.net/weixin_34074740/article/details/92645170?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-2.control
        }).sorted((menu1,menu2) -> {
            return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }


    /**
     *  利用catelogId查完整路径【父亲，儿子，孙子】
     * */
    public Long[] findCateLogPath(Long catelogId){
        List<Long> paths = new ArrayList<>();
        //递归查询
        paths = findParentPath(catelogId,paths);
        // 收集的时候是逆序 前端是顺序显示的 所以用集合工具类给它逆序一下
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCascade(CategoryEntity category) {
        //更新自己
        this.updateById(category);
        //更新关联表
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 递归收集所有父节点
     */
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }
}